<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if(!class_exists('Api_hd_survey')){
    class Api_hd_survey extends CI_Controller {

        protected $_action = '';

        protected $_distance = 325;

        private $_source = '';
        private $_type = '';

        public function __construct(){
            parent::__construct();
            $this->load->model('Apilogmodel','m_api_log');
            $this->load->model('Usermodel','m_user');
            $this->load->model('Appmodel','m_app');
            $this->load->model('Smsmodel','m_sms');
            $this->load->model('Hdsurveymodel','m_survey');
            $this->load->database();

            // $this->response->setDetail('调查暂停中!');
            // $this->response->responseExit();
            // $this->_source = $this->input->post('source');
            // $game_deadline = $this->m_config->getConfig(HONDA_DEADLINE);
            // if(!empty($game_deadline) && strtotime($game_deadline) < time()) {
            //     $this->response->setDetail('活动已结束!');
            //     $this->response->responseExit();
            // }
        }

        public function __destruct() {
            // $this->session->unset_userdata($this->_action);
            $customer = $this->session->userdata('hd_survey_customer');
            $info = $this->input->post();
            $result = $this->response->getResult();
            @$this->m_api_log->createApiLog(array(
                'ip_address' => $this->input->ip_address(),
                'customer_id' => empty($customer) ? 0 :  $customer['customer_id'],
                'request_uri' => $_SERVER['REQUEST_URI'],
                'post_data' => json_encode($info,JSON_UNESCAPED_UNICODE),
                'result_data' => json_encode($result,JSON_UNESCAPED_UNICODE),
                'api_log_time_create' => NOW,
                'ua' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
                // 'terminal' => TERMINAL_WEIXIN,
            ));

            $this->db->close();
        }


        public function initCustomer() {
            $this->validate->setRule('openid','string');
            $this->validate->setRule('openid_md5','string');
            $this->validate->setRule('nickname','string');
            $this->validate->setRule('nickname','notnull',false);
            $this->validate->setRule('sex','integer');
            $this->validate->setRule('sex','notnull',false);
            $this->validate->setRule('province','string');
            $this->validate->setRule('province','notnull',false);
            $this->validate->setRule('city','string');
            $this->validate->setRule('city','notnull',false);
            $this->validate->setRule('country','string');
            $this->validate->setRule('country','notnull',false);
            $this->validate->setRule('headimgurl','string');
            $this->validate->setRule('headimgurl','notnull',false);
            $this->validate->setRule('create_code','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if(md5($info['openid'].FREEDOM_WAR_SALT) != $info['openid_md5']) {
                $this->response->setDetail('请勿恶意访问!');
                $this->response->responseExit();
            }
            unset($info['openid_md5']);

            $user = $this->m_user->getUserByCode($info['create_code']);
            if(empty($user)) {
                $this->response->setDetail('商户编码错误！');
                $this->response->responseExit();
            }
            $info['user_id'] = $user['user_id'];

            // $info['nickname'] = urlencode($info['nickname']);

            $customer = $this->m_survey->getCustomerByOpenid($info['openid']);
            if(!empty($customer) && $customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }
            // if(!empty($customer) && ($customer['nickname'] != $info['nickname'] || $customer['headimgurl'] != $info['headimgurl'])){
            //     $info['customer_id'] = $customer['customer_id'];
            //     $this->m_survey->editCustomer($info);
            //     $customer = $this->m_survey->getCustomer($info['customer_id']);
            // }
            //
            //
            $this->session->set_userdata('hd_survey_customer',$customer);
            $this->session->set_userdata('hd_survey_customer_enter_time',NOW);

            $this->session->set_userdata('survey_customer_info',$info);
            $this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->setAddon(array(
                'bind' => !empty($customer),
                'join' => !empty($customer) && $customer['content_id'] > 0,
            ));
            $this->response->responseExit();
        }

        private function _getRandomCode() {
        	// $code = uniqid();
        	$code = '';
        	$str ='1234567890';
        	$len = strlen($str);
        	for($i=0;$i<4;$i++) {
        		$code = $str[rand()%$len].$code;
        	}
        	return $code;
        }

        public function getCode() {
            $survey_customer_info = $this->session->userdata('survey_customer_info');
            if(empty($survey_customer_info)) {
                $this->response->setDetail('请刷新重试');
                $this->response->responseExit();
            }

            $this->validate->setRule('customer_phone','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if(!preg_match("/^1[0-9]\d{9}$/i", $info['customer_phone'])){
                $this->response->setDetail('请输入正确的手机号码!');
                $this->response->responseExit();
            }

            // if($this->m_survey->checkPhoneExisted($info['customer_phone'])) {
            // 	$this->response->setDetail('手机号['.$info['customer_phone'].']已绑定微信!');
            //     $this->response->responseExit();
            // }

            $code = $this->_getRandomCode();
            if(ONLINE) {
                $sms_content = '您的验证码为'.$code.',有效期10分钟【广汽本田】';
                $result = $this->m_sms->sendSms($info['customer_phone'],$sms_content,'hd_survey');
                if($result != 1) {
                    $this->response->setDetail('发送验证码错误['.$result.']!');
                    $this->response->responseExit();
                }
            }

            $this->session->set_userdata('hd_suervey_'.$info['customer_phone'],$code);
            $this->session->set_userdata('hd_suervey_'.$info['customer_phone'].'_time',time());

            $this->response->setSuccess();
            if(!ONLINE) $this->response->setAddon(array('code' => $code));
            $this->response->responseExit();
        }

        public function bind() {
            $survey_customer_info = $this->session->userdata('survey_customer_info');
            if(empty($survey_customer_info)) {
                $this->response->setDetail('请刷新重试');
                $this->response->responseExit();
            }

            $this->validate->setRule('customer_phone','string');
            $this->validate->setRule('code','string');
            $this->validate->setRule('customer_car_number','string');
            $this->validate->setRule('customer_car_number','notnull',false);
            $this->validate->setRule('customer_car_number','optional',true);
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if(!preg_match("/^1[0-9]\d{9}$/i", $info['customer_phone'])){
                $this->response->setDetail('请输入正确的手机号码!'.$info['customer_phone']);
                $this->response->responseExit();
            }

            // if($this->m_survey->checkPhoneExisted($info['customer_phone'])) {
            // 	$this->response->setDetail('手机号['.$info['customer_phone'].']已绑定微信!');
            //     $this->response->responseExit();
            // }

            $code = $this->session->userdata('hd_suervey_'.$info['customer_phone']);
            $code_time = $this->session->userdata('hd_suervey_'.$info['customer_phone'].'_time');
            if($code != $info['code']) {
                $this->response->setDetail('短信验证码错误!');
                $this->response->responseExit();
            }
            if(time() - intval($code_time) > 10*60) {
                $this->response->setDetail('短信验证码已过期!');
                $this->response->responseExit();
            }
            unset($info['code']);
            $survey_customer_info['customer_phone'] = $info['customer_phone'];
            $survey_customer_info['customer_car_number'] = $info['customer_car_number'];
            $survey_customer_info['customer_time_create'] = NOW;
            $customer_id = $this->m_survey->createCustomer($survey_customer_info);
            if($customer_id == 0) {
                $this->response->setDetail('绑定失败，请重试!');
                $this->response->responseExit();
            }

            $customer = $this->m_survey->getCustomer($customer_id);
            $this->session->set_userdata('hd_survey_customer',$customer);
            $this->session->set_userdata('hd_survey_customer_enter_time',NOW);

            $this->response->setSuccess();
            $this->response->responseExit();
        }

        public function submitSurvey() {
            $customer = $this->session->userdata('hd_survey_customer');
            if(empty($customer)) {
                $this->response->setDetail('请勿恶意访问!');
                $this->response->responseExit();
            }
            if($customer['content_id'] > 0) {
                $this->response->setDetail('您已参与!');
                $this->response->responseExit();
            }
            $questions = [3,3,4,3,3];
            foreach ($questions as $i => $len) {
                for($j=0; $j < $len; $j++) {
                    $this->validate->setRule('question_'.(intval($i)+1).'_'.(intval($j)+1),'integer');
                }
            }
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail('请填写完整!');
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();
            $info['customer_id'] = $customer['customer_id'];
            $info['customer_time_create'] = NOW;
            $info['user_id'] = $customer['user_id'];
            $score = 0;
            foreach ($questions as $i => $len) {
                for($j=0; $j < $len; $j++) {
                    $score += intval($info['question_'.(intval($i)+1).'_'.(intval($j)+1)]);
                }
            }
            $info['score'] = $score;
            $start_time = $this->session->userdata('hd_survey_customer_enter_time');
            $cost = empty($start_time) ? 0 : (strtotime(NOW) - strtotime($start_time));
            $info['customer_time_start_survey'] = empty($start_time) ? '0000-00-00 00:00:00' : $start_time;
            $info['customer_time_cost'] = $cost;
            $content_id = $this->m_survey->createContent($info);
            $this->m_survey->editCustomer(array(
                'customer_id' => $customer['customer_id'],
                'content_id' => $content_id,
                'customer_time_survey' => NOW,
                'customer_time_survey_start' => $info['customer_time_start_survey'],
                'customer_survey_cost' => $info['customer_time_cost'],
            ));
            $customer = $this->m_survey->getCustomer($customer['customer_id']);
            $this->session->set_userdata('hd_survey_customer',$customer);

            $this->response->setSuccess();
            $this->response->responseExit();
        }


        public function sendSmsTest() {
          $phone = '18618419289';
          $sms_content = '测试您的验证码为888888,有效期10分钟【广汽本田】';
          $result = $this->m_sms->sendSms($phone,$sms_content,'hd_survey');
          if($result != 1) {
              $this->response->setDetail('发送验证码错误['.$result.']!');
              $this->response->responseExit();
          }
          $this->response->setDetail('发送验证码成功!');
          $this->response->responseExit();
        }

        public function dbview() {
            die();
            $data['desc'] = '清除本田问卷数据';
            $data['ctrlName'] = $this->uri->rsegments[1];
            $this->load->view('zm/clear_db',$data);
        }
        public function clearDb(){
            die();
            $this->db->truncate('hd_survey_customer');
            $this->db->truncate('hd_survey_customer');


            $this->response->setSuccess();
            $this->response->setDetail('清除成功!');
            $this->response->responseExit();
        }
    }

}
